<?php

/**
 * Numeric.php
 *
 * Holds class Pagination_Numeric
 *
 * @package Library
 * @subpackage Pagination
 */

/**
 * Pagination_Numeric
 *
 * Paginates resultsets numerically
 *
 * @package Library
 * @subpackage Pagination
 */
class Pagination_Numeric {

	/**
	 * Active page
	 * @var string $_active
	 */
	protected $_active = 1;

	/**
	 * Current page
	 * @var $_current
	 */
	protected $_current = 1;

	/**
	 * Pages
	 * @var array $_page
	 */
	protected $_page;

	/**
	 * Items per page
	 * @var integer
	 */
	protected $_perPage;

	/**
	 * Total pages
	 * @var integer $_totalPages
	 */
	protected $_totalPages;

	/**
	 * Constructor
	 *
	 * @param Mvc_Request $request
	 * @param string $param
	 * @param integer $total
	 * @param integer $perPage
	 * @return void
	 */
	public function __construct(Mvc_Request $request, $param, $total, $perPage) {
		$total = (0 == $total) ? 1 : $total;

		$this->_perPage    = $perPage;
		$this->_totalPages = ceil($total / $this->_perPage);
		$this->_page       = range(1, $this->_totalPages);

		// Set active page
		try {
			if($request->hasParam($param))
				$active = $request->getParam($param);
			elseif(isset($request->post->$param))
				$active = $request->post->$param;
			else
				throw new Exception("no paramater defined");
				
			if(0 >= $active) {
				$active = 1;
			}
			$this->_active = min($this->_totalPages, $active);
		}
		catch(Exception $e) {
			$this->_active = 1;
		}
	}

	/**
	 * Returns active page
	 *
	 * @return string
	 */
	public function getActive() {
		return (string) $this->_active;
	}

	/**
	 * Returns item range
	 *
	 * @return array
	 */
	public function getItems() {
		return array(
			'limit'  => $this->_perPage,
			'offset' => ($this->_active - 1) * $this->_perPage,
		);
	}

	/**
	 * Returns pages
	 *
	 * @return array
	 */
	public function getPages() {
		if(11 > $this->getTotalPages()) {
			return $this->_page;
		}
		if(0 > $this->getActive() - 6) {
			return array_slice($this->_page, 0, 11);
		}
		if($this->getTotalPages() < $this->getActive() + 5) {
			return array_slice($this->_page, -11);
		}
		return array_slice($this->_page, $this->getActive() - 6, 11);
	}

	/**
	 * Returns total pages
	 *
	 * @return integer
	 */
	public function getTotalPages() {
		return $this->_totalPages;
	}

}
